<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Promotion_lib
 *
 * @author Administrator
 */
class Promotion_lib {

  var $ci;

  public function __construct() {
    $this->ci = & get_instance();
  }

  public function download($data) {
    $end_user = $this->ci->db->get_where(DB_TABLE_END_USER, array('id' => $data['end_user_id']), 1, 0)->result_array();
    if (!empty($end_user)) {
      $user = $this->ci->db->get_where(DB_TABLE_USER, array('id' => $end_user[0]['user_id']), 1, 0)->result_array();
      if (!empty($user)) {
        $promotion = $this->ci->db->get_where(DB_TABLE_PROMOTION, array('id' => $data['promotion_id']), 1, 0)->result_array();
        if (!empty($promotion)) {
          $end_user = $end_user[0];
          $user = $user[0];
          $promotion = $promotion[0];
          $this->ci->load->library('sendEmail');
          $send = $this->ci->sendemail->sendEmailByTemplate(array_merge($end_user, $user, $promotion, $data, array(
                              'link_promotion' => site_url('promotion/show/' . $data['promotion_id']),
                              'from' => $this->ci->setting_model->item('contact_email'),
                              'to' => $end_user['email'])), 'download_promotion');
          return $send;
        }
      }
    }
    return false;
  }

  public function list_favorite_promotion($end_user_id, $max, $offset = 0) {
    $promotions_id = $this->ci->promotion_favorite_model->get_all(
                    array('end_user_id' => $end_user_id), null, null, null, null, 
            null, null, null, null, null, null, null, array('date_create' => 'desc'), $max, $offset);
    $ids = array(0);
    foreach ($promotions_id as $id) {
      $ids[] = $id['promotion_id'];
    }
    if(!empty ($ids)){
      return $this->ci->promotion_model->get_all(null, null, array('id' => $ids));
    }
    return array();
  }

  public function get_geo_by_address($address) {
    $url = 'http://maps.google.com/maps/geo?output=json&key=' .
            $this->ci->setting_model->item('googlemap_api') . '&q=' . urlencode($address);
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    curl_close($curl);
    $data = json_decode($data);
    if ($data && isset($data->Placemark)) {
      return array('latitude' => $data->Placemark[0]->Point->coordinates[1],
          'longitude' => $data->Placemark[0]->Point->coordinates[0]);
    }
    return null;
  }

  public function toRadian($val) {
    return (pi() / 180) * $val;
  }

  public function count_distance($lat1, $lng1, $lat2, $lng2) {
    if ($lat1 <= -90 || $lat1 >= 90 || $lng1 <= -180 || $lng1 >= 180
            || $lat2 <= -90 && $lat2 >= 90 || $lng2 <= -180 || $lng2 >= 180) {
      return -1;
    }
    $R = 3959; // 6371;
    $dLat = $this->toRadian($lat2 - $lat1);
    $dLon = $this->toRadian($lng2 - $lng1);
    $a = sin($dLat / 2) * sin($dLat / 2) + cos($this->toRadian($lat1)) * cos($this->toRadian($lat2)) * sin($dLon / 2) * sin($dLon / 2);
    $c = 2 * asin(min(1, sqrt($a)));
    $d = $R * $c;
    return $d;
  }
  
  public function list_promotion_near_point($lat,$lng, $distance = 50){
    $conditions = array('status' => PROMOTION_PUBLISH, 'start_date <= ' => time(), 'end_date >= ' => time(), 'remain > ' => 0);
    if (userdata('country_id'))
      $conditions['country_id'] = userdata('country_id');
    if (userdata('state_id'))
      $conditions['state_id'] = userdata('state_id');
    if (userdata('city_id'))
      $conditions['city_id'] = userdata('city_id');
    $promotions = $this->ci->promotion_model->get_all($conditions, null, null, null, null, null, null, null, null, 
	  null, null, null, array('end_date' => 'asc'));
    $data = array();
    foreach($promotions as $promotion){
	  $p_distance = $this->count_distance($lat, $lng, $promotion['lat'], $promotion['lng']);
	  if($p_distance <= $distance){
        $data[$p_distance] = $promotion;
	  }
    }
    ksort($data);
    return array_values($data);
  }
  
  public function list_promotion_near_address($address){
    $geo = $this->get_geo_by_address($address);
    if($geo){
      return $this->list_promotion_near_point($geo['latitude'], $geo['longitude']);
    }
    return array();
  }

}